package com.ymttest.business.service.shenqi;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import com.shop2cn.iapi.shenqisettlement.parameter.OnHpSettledReq;
import com.shop2cn.iapi.shenqisettlement.parameter.SaveProxyFissionConfigReq;
import com.shop2cn.iapi.shenqisettlement.service.OnHpSettledCall;
import com.shop2cn.iapi.shenqisettlement.service.SaveProxyFissionConfigCall;
import com.shop2cn.iapi.sqoptrade.parameter.utill.Utils;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.shenqisettlement.CurrencyConfig;
import com.ymttest.database.sharding.db.sharding.model.PaymentPo;
import com.ymttest.database.sqlwapper.shenqisettlement.CurrencyConfigWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.CurrencyExchangeRateWrapper;

public class ShenqiSettlementService {
	
	private static OnHpSettledReq hpSettledReq = new OnHpSettledReq();
	private static OnHpSettledCall hpSettledCall = new OnHpSettledCall();
	
	private static CurrencyExchangeRateWrapper currencyExchangeRateWrapper = new CurrencyExchangeRateWrapper();

	public static BigDecimal getSellCurrencyVsBuyCurrencyRate(String sellCurrency, String buyCurrency) {
		
		BigDecimal bidVsSettlementExchangeRate = null;
		
		if (sellCurrency.equalsIgnoreCase(buyCurrency))
			return BigDecimal.ONE;
		
		bidVsSettlementExchangeRate = currencyExchangeRateWrapper
				.selectBySellAndBuy(sellCurrency, buyCurrency)
				.getExchange_rate();
		
		if (null == bidVsSettlementExchangeRate) {
			
			BigDecimal bidCurrencyVsUSDRate = currencyExchangeRateWrapper
					.selectBySellAndBuy(sellCurrency, "USD")
					.getExchange_rate();

			BigDecimal USDVsSellerCurrencyRate = currencyExchangeRateWrapper
					.selectBySellAndBuy("USD", buyCurrency)
					.getExchange_rate();

			bidVsSettlementExchangeRate = bidCurrencyVsUSDRate
					.multiply(USDVsSellerCurrencyRate);
		}
		
		return bidVsSettlementExchangeRate;
	}
	
	/**
	 * 代购神器订单结算job
	 *
	 * @return
	 */
	public static void doSettlement() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/doSettlement");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 通过买入/卖出币种，进行汇率换算
	 * 
	 * @param sellAmount
	 *            卖出的价格
	 * @param buyCurrency
	 *            买入币种
	 * @param sellCurrency
	 *            卖出币种
	 * @return
	 * @throws Exception
	 */
	public static HashMap<String, BigDecimal> getAmountByCurrency(
			BigDecimal sellAmount, String buyCurrency, String sellCurrency) {

		// 先更新费率
		refreshExchangeRateConfig();

		String exchangeRate = "";
		BigDecimal amount = BigDecimal.ZERO;
		BigDecimal settleRate = BigDecimal.ZERO;
		CurrencyConfigWrapper wrapper = new CurrencyConfigWrapper();
		CurrencyConfig currencyConfig = wrapper
				.selectByPrimaryKey(sellCurrency);

		if (buyCurrency.equalsIgnoreCase("CNY"))
			exchangeRate = currencyConfig.getExchange_rmb_original_value();
		else
			exchangeRate = currencyConfig.getExchange_usd_original_value();

		String[] exhangeRateRatio = exchangeRate.split(" ");
		String currencyRatio = exhangeRateRatio[0];
		String priceRatio = exhangeRateRatio[1];

		String[] currencyRatioArray = currencyRatio.split("/");
		String[] priceRatioArray = priceRatio.split("/");
		String currencyRatioArrayLeft = currencyRatioArray[0];

		if (buyCurrency.equalsIgnoreCase(currencyRatioArrayLeft)) {

			amount = sellAmount.divide(new BigDecimal(priceRatioArray[1]), 2,
					RoundingMode.DOWN);
			settleRate = BigDecimal.ONE.divide(new BigDecimal(
					priceRatioArray[1]), 6, RoundingMode.HALF_DOWN);
		} else {

			amount = sellAmount.multiply(new BigDecimal(priceRatioArray[0]))
					.setScale(2, RoundingMode.HALF_DOWN);
			settleRate = new BigDecimal(priceRatioArray[0]);
		}

		HashMap<String, BigDecimal> map = new HashMap<String, BigDecimal>();

		map.put("amount", amount);
		map.put("settleRate", settleRate);

		return map;
	}

	/**
	 * 更新最新汇率
	 * 
	 * @return
	 */
	public static void refreshExchangeRateConfig() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/executeRefreshExchangeRateConfigTask");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 生成账户账单
	 * 
	 * @return
	 */
	public static void generateAccountDataPerDay() {

		YmatouEasyCall generateAccountDataPerDayCall = new YmatouEasyCall("",
				"POST", "JSON");

		generateAccountDataPerDayCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/generateAccountDataPerDay");

		generateAccountDataPerDayCall.setData("{}");

		try {
			generateAccountDataPerDayCall.callService();

			Logger.comment(generateAccountDataPerDayCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 设置用户平台费率
	 * 
	 * @return
	 */
	public static void setUserPlatformFeeSetting(Long userId, int rateId) {

		// 如果当前用户存在费率，则设置费率
		if (isExistPlatformFee(userId))
			return;
		else {

			YmatouEasyCall setUserPlatformFeeSettingCall = new YmatouEasyCall(
					"", "POST", "JSON");
			StringBuilder setUserPlatformFeeSettingString = new StringBuilder();

			setUserPlatformFeeSettingString.append("{\"userId\":" + userId);
			setUserPlatformFeeSettingString.append(", \"rateId\":" + rateId
					+ "}");

			setUserPlatformFeeSettingCall
					.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/setUserPlatformFeeSetting");

			setUserPlatformFeeSettingCall
					.setData(setUserPlatformFeeSettingString.toString());

			try {
				setUserPlatformFeeSettingCall.callService();

				Logger.comment(setUserPlatformFeeSettingCall.getReturnData());

			} catch (Exception e) {

				e.printStackTrace();
			}
		}
	}

	public static boolean isExistPlatformFee(long userId) {

		YmatouEasyCall getSellAmountListCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuilder getSellAmountListString = new StringBuilder();

		getSellAmountListString.append("{\"userIdList\":[" + userId + "]}");

		getSellAmountListCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/getSellAmountList");

		getSellAmountListCall.setData(getSellAmountListString.toString());

		try {
			getSellAmountListCall.callService();

			Logger.comment(getSellAmountListCall.getReturnData());

			JSONObject sellAmountVo = new JSONObject(
					getSellAmountListCall.getReturnData())
					.optJSONObject("result").optJSONArray("sellAmountVoList")
					.getJSONObject(0);

			Double directSellRate = sellAmountVo.getDouble("directSellRate");
			Double proxySellRate = sellAmountVo.getDouble("proxySellRate");

			// 如果不等于默认费率，则当前用户存在费率
			if (Utils.zeroIfNull(directSellRate) != 1.2
					&& Utils.zeroIfNull(proxySellRate) != 1.6)
				return true;
			else
				return false;

		} catch (Exception e) {

			e.printStackTrace();
			return false;
		}
	}
	
	public static void onHpSettled(long paymentId, PaymentPo payment,
			String shengPayRate, int count) throws Exception {

		if (count < 6) {

			hpSettledReq.setTradingId(paymentId);
			hpSettledReq.setOrderAmount(payment.getRealPaidAmount());
			hpSettledReq.setSettleCurrency(payment.getSettleCurrency());
			hpSettledReq
					.setSettleAmount(payment.getRealForeignAmount() != null ? payment
							.getRealForeignAmount() : payment
							.getForeignAmount());

			if (shengPayRate != null) {

				hpSettledReq.setSettleFee(payment.getRealPaidAmount().multiply(
						new BigDecimal(shengPayRate)));
			}

			hpSettledCall.setData(hpSettledReq);
			hpSettledCall.callService();

			if (!"ok".equalsIgnoreCase(hpSettledCall.getReturnData())) {

				Thread.sleep(3000 + count * 2000);
				count++;
				onHpSettled(paymentId, payment, shengPayRate, count);
			}
		} else {

			throw new Exception();
		}
	}
	
	public static void executeCancelProviderSettlementDetailTask()
			throws Exception {

		YmatouEasyCall executeCancelProviderSettlementDetailTaskCall = new YmatouEasyCall(
				"", "POST", "JSON");
		StringBuilder executeCancelProviderSettlementDetailTaskString = new StringBuilder();

		executeCancelProviderSettlementDetailTaskString.append("{}");

		executeCancelProviderSettlementDetailTaskCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/executeCancelProviderSettlementDetailTask");

		executeCancelProviderSettlementDetailTaskCall
				.setData(executeCancelProviderSettlementDetailTaskString
						.toString());

		executeCancelProviderSettlementDetailTaskCall.callService();

		Thread.sleep(3000);
	}
	
	/**
	 * 退款失败结算单进行结算
	 */
	public static void executeRefundFailSettlementTask() {

		YmatouEasyCall executeRefundFailSettlementTaskCall = new YmatouEasyCall(
				"", "POST", "JSON");

		executeRefundFailSettlementTaskCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/executeRefundFailSettlementTask");

		executeRefundFailSettlementTaskCall.setData("{}");

		try {
			executeRefundFailSettlementTaskCall.callService();

			Logger.comment(executeRefundFailSettlementTaskCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 代购神器分销裂变结算
	 *
	 * @return
	 */
	public static void executeProxyFissionSettlementTask() {

		YmatouEasyCall executeProxyFissionSettlementTaskCall = new YmatouEasyCall(
				"", "POST", "JSON");

		executeProxyFissionSettlementTaskCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/executeProxyFissionSettlementTask");

		executeProxyFissionSettlementTaskCall.setData("{}");

		try {
			executeProxyFissionSettlementTaskCall.callService();

			Logger.comment(executeProxyFissionSettlementTaskCall
					.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public static void saveProxyFissionConfigCall(
			SaveProxyFissionConfigReq saveProxyFissionConfigReq)
			throws ClientProtocolException, IOException {

		SaveProxyFissionConfigCall saveProxyFissionConfigCall = new SaveProxyFissionConfigCall();

		saveProxyFissionConfigCall.setData(saveProxyFissionConfigReq);
		saveProxyFissionConfigCall.callService();
	}
	
	/**
	 * 盛付通聚合分账job
	 * 
	 * @return
	 */
	public static void executeShengPayMerchantSharingConvergeTask() {

		YmatouEasyCall executeShengPayMerchantSharingConvergeTaskCall = new YmatouEasyCall("", "POST", "JSON");

		executeShengPayMerchantSharingConvergeTaskCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/executeShengPayMerchantSharingConvergeTask");

		executeShengPayMerchantSharingConvergeTaskCall.setData("{}");

		try {
			executeShengPayMerchantSharingConvergeTaskCall.callService();

			Logger.comment(executeShengPayMerchantSharingConvergeTaskCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 供货商线下结算
	 * 
	 * @param sellerId
	 * @return
	 */
	public static void doGoodsOwnerOfflineSettlement() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/doGoodsOwnerOfflineSettlement");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 定金罚没结算job
	 * 
	 * @param sellerId
	 * @return
	 */
	public static void doEarnestPunishmentSettlement() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/doEarnestPunishmentSettlement");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
}
